package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Album;
import cn.edu.seu.herald.informationplatform.dao.database.AlbumDao;

public class FirstAlbumCoverRequired implements Filter {
	
	public static final String COVER_PICTURES_NAME = "albums";
	
	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		try {
			String leagueIdParam = request.getParameter(
					LeagueSpecified.PARAM_NAME_OF_LEAGUE_ID);
			int leagueId = Integer.valueOf(leagueIdParam);
			AlbumDao access = AlbumDao.getDao();
			Map<Integer, Album> albums = access.getAlbumsByLeagueId(leagueId);
			request.setAttribute(COVER_PICTURES_NAME, subMap(albums, 4));
		} catch (NumberFormatException e) {
			httpResponse.sendError(400);
			return;
		} catch (SQLException e) {
			httpResponse.sendError(500);
			return;
		}

		chain.doFilter(request, response);
	}
	
	private static Map<Integer, Album> subMap(Map<Integer, Album> map, int limit) {
		Map<Integer, Album> result = new HashMap<Integer, Album>();
		int counter = 1;
		for (Entry<Integer, Album> e: map.entrySet()) {
			if (counter > limit) {
				break;
			}
			result.put(e.getKey(), e.getValue());
			++counter;
		}
		return result;
	}

}
